// Logistics/components/transitPoint.js
/*{
单元名称：当前位置信息选择运输点组件js
单元功能：根据当前位置匹配附近运输点，单个不能选择，多个可手动选择
所属模块功能：
创建人：yan
创建时间：230830
修改人：
修改时间：
}*/
import {config} from "../../../utils/config";

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    //显示弹窗标识，监听显示获取当前定位并获取附近站点
    show: {
      type: Boolean,
      observer(val){
        if (val) {
          this.wxLocation().then(res => {
            console.log(res);
            let{address,location,} = res,
              {info} = this.data;
            this.setData(
              {info: {...info,weidu:location.lat,jingdu:location.lng,weizhi:address}})
            this.getTransitPoint(location);
          },() =>{
            this.setData({info: {jiedian: this.data.info.jiedian}})
            wx.hideLoading();
            wx.showModal({
              title: '定位服务未打开',
              content: '请在系统设置中打开位置授权，以便我们为您提供更好的服务',
              confirmText: '确定',
              showCancel: false,
              success: (res) => {
                if(res.confirm) {
                  wx.navigateTo({url:'/SlagCar/OpenLocationGuide/OpenLocationGuide'})
                }
              },
            });
          })

          let user_name = wx.getStorageSync('user_name');
          this.setData({['info.user_name']: user_name});
        }
      }
    },

  //传入参数显示
    info: {
      type: Object,
      value: {}
    },
  //  货物列表
    list: {
      type: Array,
      value: []
    }

  },

  /**
   * 组件的初始数据
   */
  data: {
    field: [
      {field_id: 'yunshudian',label: '运输点',type: 'picklist',option: [],optionId: 'row_id',optionName: 'mingchen',is_null: true},
      {field_id: 'jingdu',label: '经度',isDisabled: true,type: 'text'},
      {field_id: 'weidu',label: '纬度',isDisabled: true,type: 'text'},
      {field_id: 'weizhi',label: '位置',isDisabled: true,type: 'textarea'},
      {field_id: 'user_name',label: '人员',isDisabled: true,type: 'text'},
      {field_id: 'jiedian',label: '节点',isDisabled: true,type: 'text'},
    ],
    defData: {},
    inputData: {},

    validFlag: false,             // 验证标识
    validObj: {},                 // 验证表单项

  },

  /**
   * 组件的方法列表
   */
  methods: {
    //关闭弹窗
    onClose(){
      this.setData({show: false})
    },

    // 记录验证表单项
    validIpt(e) {
      let { validObj, } = this.data
      this.data.validObj = {
        ...validObj,
        ...e.detail,
      };
    },
    //验证数据
    validForm(validObj){
      return new Promise((resolve, reject) => {
        let valid = Object.values(validObj).includes(false) ? false : true;
        resolve(valid)
      })
    },

  //  确定
    onConfirm(){
      this.data.validObj = {}
      this.setData({
        validFlag: !this.data.validFlag,
      });

      let formObj = this.data.info,
        validObj = this.data.validObj;
      this.validForm(validObj).then(valid => {
        if(valid) { // 表单验证通过
          console.log('表单验证通过', formObj);

          this.triggerEvent('confirm',{info:this.data.info});

        } else {  // 表单验证不通过
          console.log('表单验证不通过')
          wx.$toast('必填项不能为空！')
        }
      })

      // this.setData({show: false})
    },

    //  字段变化
    bindChange(e){
      let {field,val,optItem} = e.detail,
        id = field.field_id || field.fieldName,
        type = field.type,
        obj = this.data.info;

      if (type === 'num' || type === 'currency' || type === 'percent'){
        val = val ? val : null
      }

      if (id === 'yunshudian' && optItem){
        let {row_id,mingchen,weizhi,weidu,jingdu} = optItem;
        this.setData({info: {...obj,yunshudian: row_id}})
      }else {
        //赋值
        this.data.info[id] = val;
      }

    },

    //  获取运输点
    getTransitPoint(latlng){
      wx.showLoading({mask: true})
      let{lat, lng} = latlng,
        post = {lat, lng},
        url = `WLAuth/FuJinYunShuDian`;
      wx.$get(5,url,post).then(res => {
        if (res.errcode != 0) return
        let rows = res.data.row || [],
          obj = {['field[0].option']: rows},
          info = this.data.info;
        this.setData({['field[0].option']: rows});
        //只有一条数据时默认填充
        if (rows.length === 1){
          let {row_id,mingchen,weizhi,weidu,jingdu} = rows[0];
          info = {...info,yunshudian: row_id}
          this.setData({info})
        }
        wx.hideLoading();
      })

    },

    //  获取当前位置
    wxLocation(){
      return new Promise((resolve,reject) => {
        // resolve({latitude:23.035508897569443 , longitude:113.11290771484374});
        wx.getLocation({
          type: 'gcj02', // 比较精确
          success: (res) => {
            console.log(res);
            this.mapGeocoder(res).then(result => {
              resolve(result.result);
            })
          },
          fail: (res) =>{
            console.log(res);
            reject();
          }
        })
      })
    },


    //腾讯地图api逆地址转换
    mapGeocoder(latlng){
      let url = 'map/tencent/ws/geocoder/location';
      let{latitude, longitude} = latlng;
      return new Promise(resolve => {
        wx.$post(2,url,{
          "key": config.mapKey,
          "location": `${latitude},${longitude}`,
          "get_poi": "",
          "poi_options": "",
          "output": "",
          "callback": ""
        },false,true).then(res =>{
          resolve(res)
        })
      })
    },

  },

})
